// pages/addproduct/addproduct.js
import baseteam from '~/utils/teamleader.js'
import basesup from '~/utils/supplier.js'
import config from '~/configs/configs'
import baseuser from '~/utils/users.js'
Page({

    /**
     * 页面的初始数据
     */
    data: {
        productName: '',
        startingPrice: '',
        supplyPrice: '',
        inventory: '',
        articleNumber: '',
        shipAddress: '',
        lightSpot: '',
        channel: '',
        brand: '',

        suoshustart: false,
        suoshu: [],
        suoshuselect: "",

        shangpinstart: false,
        shangpinlist: [],
        shangpinselect: "",

        baozhangstart: false,
        baozhanglist: [],
        baozhangselect: "",

        shixiaostart: false,
        shixiaolist: ['24h', '72h'],
        shixiaoselect: "",

        tiaojianstart: false,
        tiaojianlist: ['5000', '5w'],
        tiaojianselect: 0,

        switchchecked: true,
        zhongzhistart: '1',

        "sqtg": [],
        // 电商销量·
        "dsxl": [],
        // 社群团购
        // file
        coverImg: [],
        slideshow: [],
        channelzhu: [],
        channelzhuchild: [],
        material: [],

        cpxq: [],

        cpgg: [],
    },
    naveback() {
        setTimeout(() => {
            wx.navigateBack()
        }, 300);
    },

    onclone() {
        this.setData({
            show1: false,

            suoshustart: false,
            shangpinstart: false,
            baozhangstart: false,
            shixiaostart: false,
            tiaojianstart: false,
        })
    },
    naveclassification() {
        wx.navigateTo({
            url: '../../pages/classification/classification',
        })
    },
    naveproductsales() {
        wx.navigateTo({
            url: `../productsales/productsales?sqtg=` + JSON.stringify(this.data.sqtg) + "&dsxl=" + JSON.stringify(this.data.dsxl),

        })
    },
    naveadddetail() {
        wx.navigateTo({
            url: `../adddetail/adddetail?cpxq=` + JSON.stringify(this.data.cpxq),
        })
    },
    navespec() {
        wx.navigateTo({
            url: `../specifications/specifications?cpgg=` + JSON.stringify(this.data.cpgg),
        })
    },
    suoshutrue() {
        this.setData({
            suoshustart: true
        })
    },
    async getsuoshu() {
        let resdata = await baseteam.zhuyinglist()
        this.setData({
            suoshu: resdata.data.result
        })
    },
    suoshuschanges(items) {
        this.setData({
            suoshuselect: items.currentTarget.dataset.select
        })
        this.onclone()
    },

    shangpintrue() {
        this.setData({
            shangpinstart: true
        })
    },
    async getshangpin() {
        let resdata = await basesup.storeClass()
        this.setData({
            shangpinlist: resdata.data.Result.records
        })
    },
    shangpinchanges(items) {
        this.setData({
            shangpinselect: items.currentTarget.dataset.select
        })
        this.onclone()
    },

    baozhangtrue() {
        this.setData({
            baozhangstart: true
        })
    },

    async getbaozhang() {
        let resdata = await basesup.parameterlist()
        for (const ins in resdata.data.result) {
            resdata.data.result[ins].select = 0
        }
        this.setData({
            baozhanglist: resdata.data.result
        })
    },
    baozhangchanges(items) {
        let setstring = `baozhanglist[${items.currentTarget.dataset.select}].select`
        if (this.data.baozhanglist[items.currentTarget.dataset.select].select == 0) {
            this.setData({
                [setstring]: 1
            })
        } else {
            this.setData({
                [setstring]: 0
            })
        }
    },
    baozhanglink() {
        let baozhangdisp = ''
        let starts = 0
        for (const aa in this.data.baozhanglist) {
            if (this.data.baozhanglist[aa].select == 1) {
                starts++
            }
        }
        if (starts == 0) {
            baozhangdisp = '无'
            this.setData({
                baozhangselect: baozhangdisp
            })
            this.onclone()
            return false
        } else {
            for (const iis in this.data.baozhanglist) {
                if (this.data.baozhanglist[iis].select == 1) {
                    baozhangdisp += this.data.baozhanglist[iis].name + ","
                }
            }
            baozhangdisp = baozhangdisp.substring(0, baozhangdisp.length - 1)
            this.setData({
                baozhangselect: baozhangdisp
            })
            this.onclone()
        }


    },

    shixiaotrue() {
        this.setData({
            shixiaostart: true
        })
    },
    shixiaochanges(items) {
        this.setData({
            shixiaoselect: items.currentTarget.dataset.select
        })
        this.onclone()
    },
    lingyangtrue() {
        this.setData({
            tiaojianstart: true
        })
    },
    onswitchChange({ detail }) {
        this.setData({
            switchchecked: detail
        });
    },
    zhongzhionChange(event) {
        this.setData({
            zhongzhistart: event.detail,
        });
    },
    gentua(items) {
        this.setData({
            tiaojianselect: items.currentTarget.dataset.select,
        });
    },

    zhuafterRead(event) {
        const { file } = event.detail;
        const { coverImg = [] } = this.data.coverImg;
        coverImg.push(...file);
        this.setData({ coverImg });
    },
    zhudel(event) {
        let coverImg = this.data.coverImg;
        coverImg.splice(event.detail.index, 1)
        this.setData({ coverImg });
    },

    slideafterRead(event) {
        const { file } = event.detail;
        const slideshow = this.data.slideshow;
        slideshow.push(...file);
        this.setData({ slideshow });
    },
    slidedel(event) {
        let slideshow = this.data.slideshow;
        slideshow.splice(event.detail.index, 1)
        this.setData({ slideshow });
    },

    qudaoafterRead(event) {
        const { file } = event.detail;
        const channelzhu = this.data.channelzhu;
        channelzhu.push(...file);
        this.setData({ channelzhu });
    },
    qudaodel(event) {
        let channelzhu = this.data.channelzhu;
        channelzhu.splice(event.detail.index, 1)
        this.setData({ channelzhu });
    },

    qudaochildafterRead(event) {
        const { file } = event.detail;
        const channelzhuchild = this.data.channelzhuchild;
        channelzhuchild.push(...file);
        this.setData({ channelzhuchild });
    },
    qudaochilddel(event) {
        let channelzhuchild = this.data.channelzhuchild;
        channelzhuchild.splice(event.detail.index, 1)
        this.setData({ channelzhuchild });
    },

    materialafterRead(event) {
        const { file } = event.detail;
        const material = this.data.material;
        material.push(...file);
        this.setData({ material });
    },
    materialdel(event) {
        let material = this.data.material;
        material.splice(event.detail.index, 1)
        this.setData({ material });
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        if (JSON.stringify(options) != undefined && JSON.stringify(options).length > 2) {
            this.setData({
                commodityid: options.id
            })
            // this.getsuoshu()

        } else {
            this.getsuoshu()
            this.getshangpin()
            this.getbaozhang()
        }

    },

    filesUpload(paths) {
        return new Promise((resolve, reject) => {
            // wx.showLoading({
            //     title: '上传中, 请稍等..',
            //     mask: true
            // })
            let uploadCount = 0; // 上传计数
            const resources = [] // 上传结果
            //上传图片
            for (const path of (Array.isArray(paths) ? paths : [paths])) {
                wx.uploadFile({
                    url: config.baseUrl + baseuser.adminossfileupload,
                    filePath: path.url,
                    name: 'file',
                    timeout: 60 * 1000,
                    success: function (res) {
                        let data = JSON.parse(res.data);
                        if (data.code == 200) {
                            resources.push(data.data.map.url)
                        }
                    },
                    complete: () => {
                        uploadCount++
                        if (resources.length == (Array.isArray(paths) ? paths.length : 1)) {
                            // wx.hideLoading()
                            if (resources.length == 0) {
                                // showToast('上传失败')
                                reject('上传失败')
                            } else {
                                // showToast(paths instanceof String ? '上传成功' : '成功上传：' + resources.length + '张')
                                resolve(resources)
                            }
                        }
                    }
                });
            }
        })
    },
    
    async bindsubmit() {
        wx.showLoading({
            title: '上传中, 请稍等..',
            mask: true
        })
        // dome循环
        // let newsqtg = this.data.sqtg
        // for (const key in newsqtg) {
        //     if (newsqtg[key].image.length != 0) {
        //         var setdata = `sqtg[${key}].image`
        //         let sqtgimages = await this.filesUpload(newsqtg[key].image)
        //         console.log(sqtgimages)
        //         this.setData({
        //             [setdata]: sqtgimages
        //         })
        //     }
        // }
        // console.log(this.data.sqtg)

        // datalistzhu = await this.filesUpload(this.data.sqtg[0].image)
        // console.log(datalistzhu)


        let newcoverImg = []
        if (this.data.coverImg.length != 0) {
            newcoverImg = await this.filesUpload(this.data.coverImg)
        }
        let newslideshow = []
        if (this.data.slideshow.length != 0) {
            newslideshow = await this.filesUpload(this.data.slideshow)
        }
        let newmaterial = []
        if (this.data.material.length != 0) {
            newmaterial = await this.filesUpload(this.data.material)
        }


        let sqtglist = this.data.sqtg
        for (const ins in this.data.sqtg) {
            if (this.data.sqtg[ins].image.length != 0) {
                let sqtgimages = await this.filesUpload(this.data.sqtg[ins].image)
                sqtglist[ins].image = JSON.stringify(sqtgimages)
            }
            if (this.data.sqtg[ins].qrCode.length != 0) {
                let sqtgimages = await this.filesUpload(this.data.sqtg[ins].qrCode)
                sqtglist[ins].qrCode = JSON.stringify(sqtgimages)
            }
        }

        let dsxllist = this.data.dsxl
        for (const ins in this.data.dsxl) {
            if (this.data.dsxl[ins].image.length != 0) {
                let dsxlimages = await this.filesUpload(this.data.dsxl[ins].image)
                dsxllist[ins].image = JSON.stringify(dsxlimages)
            }
            if (this.data.dsxl[ins].qrCode.length != 0) {
                let dsxlimages = await this.filesUpload(this.data.dsxl[ins].qrCode)
                dsxllist[ins].qrCode = JSON.stringify(dsxlimages)
            }
        }

        let cpxqlist = this.data.cpxq
        for (const ins in this.data.cpxq) {
            if (typeof (this.data.cpxq[ins].content) == 'object') {
                let cpxqimages = await this.filesUpload(this.data.cpxq[ins].content)
                cpxqlist[ins].content = JSON.stringify(cpxqimages)
            }

        }

        let switchly = 1
        if (this.data.switchchecked == false) {
            switchly = 2
        }

        let newcpgg = this.data.cpgg
        for (const innn in this.data.cpgg) {
            newcpgg[innn].params = JSON.stringify(this.data.cpgg[innn].params)
        }

        let reqdata = {
            productName: this.data.productName,
            startingPrice: this.data.startingPrice,
            supplyPrice: this.data.supplyPrice,
            inventory: this.data.inventory,
            articleNumber: this.data.articleNumber,
            shipAddress: this.data.shipAddress,
            lightSpot: this.data.lightSpot,
            channel: this.data.channel,

            "coverImg": JSON.stringify(newcoverImg),
            "slideshow": JSON.stringify(newslideshow),
            "category": this.data.suoshuselect,
            "menuBar": this.data.shangpinselect,
            "deliveryTime": this.data.shixiaoselect,
            "safeguard": this.data.baozhangselect,
            "channelText": '',
            "material": JSON.stringify(newmaterial),
            "brand": this.data.brand,

            cpgg: newcpgg,
            cpxl: [ ...sqtglist, ...dsxllist ],
            cpxq: cpxqlist,
            lytj: [{
                "status":  Number(switchly), 
                "returnStatus": Number(this.data.zhongzhistart),
                "getCondition": Number(this.data.tiaojianlist[this.data.tiaojianselect]),
            }]
        }

        let resdata = await basesup.addproduct(reqdata)
        if (resdata.code == 200) {
            wx.hideLoading()
            wx.showToast({
                title: '上传成功,等待审核',
                icon: 'success',
                duration: 2000
            })
            setTimeout(() => {
                this.naveback()
            }, 1800);
        } else {
            wx.hideLoading()
            wx.showToast({
                title: '上传失败',
                icon: 'error',
                duration: 2000
            })
        }
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.getshangpin()
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})